package servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.smartam.leeloo.common.OAuth;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import util.HttpUtil;
import util.Logger;
import constant.Constant;

/**
 * Servlet implementation class ClientServlet
 */
@WebServlet(Constant.DEFAULT_CLIENT)
public class ClientServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ClientServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	private String getServerURI(HttpServletRequest request) {
		return request.getParameter(Constant.SYNC_SERVER)
				+ Constant.DEFAULT_URL_RESOURCESERVER;
	}
	private String generateHttpParam(HttpServletRequest request, String name){
		return HttpUtil.httpParam(name, request.getParameter(name));
	}
	private String generateHttpParam(HttpServletRequest request, String name, String valuename){
		return HttpUtil.httpParam(name, request.getParameter(valuename));
	}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Logger.Log("Client...");
		try {
			HttpClient httpclient = new DefaultHttpClient();
			Logger.Log("getServerURI " + this.getServerURI(request));
			String resourceurl = this.getServerURI(request) + "?";
			resourceurl += this.generateHttpParam(request, OAuth.OAUTH_ACCESS_TOKEN);
			resourceurl += this.generateHttpParam(request, OAuth.OAUTH_CLIENT_ID);
			resourceurl += this.generateHttpParam(request, OAuth.OAUTH_CLIENT_SECRET);
			resourceurl += this.generateHttpParam(request, Constant.SYNC_AP);
			resourceurl += this.generateHttpParam(request, Constant.SYNC_CALLBACKURI);
			if(Constant.HOST_AWS.equals(request.getParameter(Constant.SYNC_SERVER))){
				resourceurl += this.generateHttpParam(request, Constant.SYNC_URL_AP_OTHER, Constant.SYNC_AWS_URL_AP_OTHER);
			}
			else{
				resourceurl += this.generateHttpParam(request, Constant.SYNC_URL_AP_OTHER, Constant.SYNC_LOCAL_URL_AP_OTHER);
			}
			
			
			/*if (request.getParameter(OAuth.OAUTH_ACCESS_TOKEN) != null) {
				resourceurl += "&"
						+ OAuth.OAUTH_ACCESS_TOKEN
						+ "="
						+ URLEncoder.encode(
								request.getParameter(OAuth.OAUTH_ACCESS_TOKEN),
								"utf-8");
			}
			if (request.getParameter(OAuth.OAUTH_CLIENT_ID) != null) {
				resourceurl += "&"
						+ OAuth.OAUTH_CLIENT_ID
						+ "="
						+ URLEncoder.encode(
								request.getParameter(OAuth.OAUTH_CLIENT_ID),
								"utf-8");
			}
			if (request.getParameter(OAuth.OAUTH_CLIENT_SECRET) != null) {
				resourceurl += "&"
						+ OAuth.OAUTH_CLIENT_SECRET
						+ "="
						+ URLEncoder
								.encode(request
										.getParameter(OAuth.OAUTH_CLIENT_SECRET),
										"utf-8");
			}
			if (request.getParameter(Constant.SYNC_AP) != null) {
				resourceurl += "&"
						+ Constant.SYNC_AP
						+ "="
						+ URLEncoder
								.encode(request.getParameter(Constant.SYNC_AP),
										"utf-8");
			}
			if (request.getParameter(Constant.SYNC_CALLBACKURI) != null) {
				resourceurl += "&"
						+ Constant.SYNC_CALLBACKURI
						+ "="
						+ URLEncoder
								.encode(request
										.getParameter(Constant.SYNC_CALLBACKURI),
										"utf-8");
			}
			if (request.getParameter(Constant.SYNC_URL_AP_OTHER) != null) {
				resourceurl += "&"
						+ Constant.SYNC_URL_AP_OTHER
						+ "="
						+ URLEncoder.encode(request
								.getParameter(Constant.SYNC_URL_AP_OTHER),
								"utf-8");
			}*/
			
			Logger.Log("resourceurl " + resourceurl);
			// org.apache.commons.logging.LogFactory a;

			HttpPost httpreq = new HttpPost(resourceurl);
			httpreq.setHeader("Content-Type",
					"application/x-www-form-urlencoded");

			// HttpParams params = new HttpParams();
			// httpreq.setParams(params);

			HttpResponse resp = httpclient.execute(httpreq);
			Logger.Log("client response status "
					+ resp.getStatusLine().getStatusCode());

			if (resp.getStatusLine().getStatusCode() == 200) {

				HttpEntity resEntity = resp.getEntity();
				if (resEntity != null) {
					InputStream stream1 = resEntity.getContent();
					BufferedReader in = new BufferedReader(
							new InputStreamReader(stream1));
					StringBuffer buffer = new StringBuffer();
					String line = "";
					while ((line = in.readLine()) != null) {
						buffer.append(line);
					}

					PrintWriter pw = response.getWriter();
					pw.write(buffer.toString());
					// System.out.println("body "+r.getBody());
					pw.flush();
					pw.close();

				}

				/*
				 * if (resEntity != null) { resEntity.consumeContent(); }
				 */
			} else if (resp.getStatusLine().getStatusCode() == Constant.STATUSCODE_OAUTH) {
				response.sendRedirect(resp.getFirstHeader("Location")
						.getValue());
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
